//
//  Authorization.m
//  各种权限
//
//  Created by 1 on 2017/11/27.
//  Copyright © 2017年 1. All rights reserved.
//

#import "Authorization.h"
#import "XPSingleton.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreTelephony/CTCellularData.h>
#import <CoreLocation/CoreLocation.h>
#import <UserNotifications/UserNotifications.h>

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif
//#ifdef NSFoundationVersionNumber_iOS_9_x_Max
//#import <UserNotifications/UserNotifications.h>
//#endif

#define kCurrentVersion [[[UIDevice currentDevice] systemVersion] floatValue]

//点击 alert 的取消按钮
static void(^_cancelBlk)(void);

@interface Authorization ()<CLLocationManagerDelegate>
@property (nonatomic, copy) void (^blk)(void);
@property (nonatomic, copy) void (^blk1)(void);
@property (nonatomic, strong) CTCellularData * cellularData;
//@property (nonatomic, strong) CLLocationManager * locationMgr;
@end

@implementation Authorization
SingletonM(Authorization)

#pragma mark - --------------- 网络 ----------------
- (CTCellularData *)cellularData {
    if (!_cellularData) self.cellularData = [[CTCellularData alloc] init];
    return _cellularData;
}
+ (BOOL)getNetAuthorizationStatusWithAlert {
    return [[Authorization sharedAuthorization] getNetAuthorizationStatusWithAlert:YES];
}
+ (BOOL)getNetAuthorizationStatusWithoutAlert {
    return [[Authorization sharedAuthorization] getNetAuthorizationStatusWithAlert:NO];
}
- (BOOL)getNetAuthorizationStatusWithAlert:(BOOL)flag {
    if (kCurrentVersion >= 9.0) {//获取网络状态
        CTCellularDataRestrictedState state = self.cellularData.restrictedState;
        if (state == kCTCellularDataRestrictedStateUnknown){
            return NO;
        }else if (state == kCTCellularDataNotRestricted){
            return YES;
        }else if (state == kCTCellularDataRestricted){
        if(flag)[Authorization showAlertWithMsg:@"已禁止使用网络功能, 是否去开启?"];
            return NO;
        }
    }
    return YES;
}
+ (void)getNetAuthorizationWithBlock:(void(^)(void))block block:(void(^)(void))block1 {
    [[Authorization sharedAuthorization] getNetAuthorizationWithBlock:block block:block1];
}
- (void)getNetAuthorizationWithBlock:(void(^)(void))block block:(void(^)(void))block1 {
    if (kCurrentVersion >= 9) { //网络状态变化
        __weak typeof(self)vcself = self;
        self.blk = block;
        self.blk1 = block1;
        self.cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state){
            dispatch_async(dispatch_get_main_queue(), ^{
              if (state == kCTCellularDataRestrictedStateUnknown){
                    if (vcself.blk1){
                        dispatch_async(dispatch_get_main_queue(), ^{
                            vcself.blk1();
                        });
                    }
                }else if (state == kCTCellularDataNotRestricted){
                    if (vcself.blk){
                        dispatch_async(dispatch_get_main_queue(), ^{
                            vcself.blk();
                        });
                    }
                }else if (state == kCTCellularDataRestricted){
                    if (vcself.blk1) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            vcself.blk1();
                        });
                    }
                }
            });
        };
    }
}
#pragma mark - --------------- 麦克风 ----------------
+ (BOOL)checkMicroPhoneAuthorizationStatus {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        return NO;
    }else if (authStatus == AVAuthorizationStatusAuthorized){
        return YES;
    } else {
        return NO;
    }
}
+ (void)getMicroPhoneAuthorizationWithBlock:(void(^)(void))block {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler: ^(BOOL granted) {
            if (granted){
                if (block) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        block();
                    });
                }
            } else {
               NSLog(@"<-- %s, %d --> 点击了不允许", __FUNCTION__, __LINE__);
          }
      }];
    }else if (authStatus == AVAuthorizationStatusAuthorized){
        if (block) {
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }
    } else {
        [Authorization showAlertWithMsg:@"已禁止使用麦克风功能, 是否去开启?"];
    }
}
#pragma mark - --------------- 相机 ----------------
+ (BOOL)checkCameraAuthorizationStatus {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        return NO;
    }else if (authStatus == AVAuthorizationStatusAuthorized){
        return YES;
    } else {
        return NO;
    }
}
+ (void)getCameraAuthorizationWithCancelBlk:(void(^)(void))cancelBlk doneBlk:(void(^)(void))doneBlk {
    _cancelBlk = cancelBlk;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                if (doneBlk) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        doneBlk();
                    });
                }
            } else {
                NSLog(@"<-- %s, %d --> 点击了不允许", __FUNCTION__, __LINE__);
                if (cancelBlk) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        cancelBlk();
                    });
                }
            }
        }];
    }else if (authStatus == AVAuthorizationStatusAuthorized){
        if (doneBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                doneBlk();
            });
        }
    }else {
        [Authorization showAlertWithMsg:@"已禁止使用相机功能, 是否去开启?"];
    }
}
#pragma mark - --------------- 相册 ----------------
+ (BOOL)checkPhotoAlbumAuthorizationStatus {
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    if (authStatus == PHAuthorizationStatusNotDetermined){
        return NO;
    }else if (authStatus == PHAuthorizationStatusAuthorized){
        return YES;
    } else {
        return NO;
    }
}
+ (void)getPhotoAlbumAuthorizationWithBlock:(void(^)(void))block {
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    if (authStatus == PHAuthorizationStatusNotDetermined){
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                if (block) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        block();
                    });
                }
            } else {
                NSLog(@"<-- %s, %d --> 点击了不允许", __FUNCTION__, __LINE__);
            }
        }];
    }else if (authStatus == PHAuthorizationStatusAuthorized){
        if (block) {
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }
    }else if (authStatus == PHAuthorizationStatusRestricted || authStatus == PHAuthorizationStatusDenied){
        [Authorization showAlertWithMsg:@"已禁止使用相册功能, 是否去开启?"];
    }
}
#pragma mark - --------------- 定位 ----------------
//+ (BOOL)checkLocationAuthorizationStatus {
//    if (![CLLocationManager locationServicesEnabled]) {
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"本设备不具备定位功能" message:nil preferredStyle:UIAlertControllerStyleAlert];
//        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
//        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
//        return NO;
//    }
//    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
//    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
//        return YES;
//    }else if (status == kCLAuthorizationStatusNotDetermined){
//        return NO;
//    } else {
//        return NO;
//    }
//}
//+ (void)getLocationAuthorizationAlways:(BOOL)type withBlock:(void(^)(void))block {
//    [[Authorization sharedAuthorization] getLocationAuthorizationAlways:type withBlock:block];
//}
//- (void)getLocationAuthorizationAlways:(BOOL)type withBlock:(void(^)(void))block {
//    if (![CLLocationManager locationServicesEnabled]) {
//        UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"本设备不具备定位功能" message:nil preferredStyle:UIAlertControllerStyleAlert];
//        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
//        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
//        return;
//    }
//    self.blk = block;
//    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
//    if (status == kCLAuthorizationStatusNotDetermined) {
//        self.locationMgr = [[CLLocationManager alloc] init];
//        _locationMgr.delegate = self;
//        type?[_locationMgr requestAlwaysAuthorization]:[_locationMgr requestWhenInUseAuthorization];
//    }else  if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse){
//        if (block) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                block();
//            });
//        }
//    }else if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted){
//        [Authorization showAlertWithMsg:@"已禁止使用定位功能, 是否去开启?"];
//    }
//}
//- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
//    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
//        if (_blk) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                _blk();
//            });
//        }
//    }
//}
#pragma mark - --------------- 推送 ----------------
+ (BOOL)checkNotificationAuthorizationStatus {
    __block BOOL isOpen = NO;
    if (kCurrentVersion >= 10.0) {
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
            if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
                isOpen = NO;
            }else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized){
                isOpen = YES;
            }else if (settings.authorizationStatus == UNAuthorizationStatusDenied){
                isOpen = NO;
            }
        }];
    }else if (kCurrentVersion >= 8.0){
        UIUserNotificationSettings * setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
        if (setting.types != UIUserNotificationTypeNone) {
            isOpen = YES;
        } else {
            isOpen = NO;
        }
    } else {
        UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        if (type != UIRemoteNotificationTypeNone) {
            isOpen = YES;
        } else {
            isOpen = NO;
        }
    }
    return isOpen;
}
+ (void)getNotificationAuthorizationWithBlock:(void(^)(void))block {
    if (kCurrentVersion >= 10.0) {
        UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
            if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
                [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
                    if (granted) {
                        if (block) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                block();
                            });
                        }
                    } else {
                        NSLog(@"<-- %s, %d --> 点击了不允许: %@", __FUNCTION__, __LINE__, error);
                    }
                }];
            }else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized){
                if (block) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        block();
                    });
                }
            }else if (settings.authorizationStatus == UNAuthorizationStatusDenied){
                [Authorization showAlertWithMsg:@"已禁止使用推送功能, 是否去开启?"];
            }
        }];
    }else if (kCurrentVersion >= 8.0){
        UIUserNotificationSettings * setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
        NSLog(@"<-- %s, %d -->  %lu", __FUNCTION__, __LINE__, (unsigned long)setting.types);
        if (setting.types != UIUserNotificationTypeNone) {
            if (block) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    block();
                });
            }
        } else {
            [Authorization showAlertWithMsg:@"已禁止使用推送功能, 是否去开启?"];
            //iOS8以前没办法得知是否是第一次注册推送, 因一般都在 "appDelegate.m" 中注册, 此处仅判断应用是否有推送权限
            //[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];
        }
    } else {
        UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        if (type != UIRemoteNotificationTypeNone) {
            if (block) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    block();
                });
            }
        } else {
            [Authorization showAlertWithMsg:@"已禁止使用推送功能, 是否去开启?"];
            //iOS8以前没办法得知是否是第一次注册推送, 因一般都在 "appDelegate.m" 中注册, 此处仅判断应用是否有推送权限
            //[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
        }
    }
}

#pragma mark - --------------- alert ----------------
+ (void)showAlertWithMsg:(NSString *)msg {
    UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:msg message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (_cancelBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _cancelBlk();
            });
        }
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"去开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }]];
    UIViewController * rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    //NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, rootVC);
    //防止重复弹
    if ([rootVC.presentedViewController isKindOfClass:[UIAlertController class]]) {
        return;
    }
    //弹窗消失后才能重弹
    if (rootVC.presentedViewController) {
        [rootVC.presentedViewController presentViewController:alertVC animated:YES completion:nil];
    } else {
        [rootVC presentViewController:alertVC animated:YES completion:nil];
    }
}

@end
